package com.monika.main.system.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.monika.main.system.factory.LogManager;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

/**
 * Author whh
 * Date 2023/04/15/ 23:12
 * <p></p>
 */
public class AddressUtil {


    // IP地址查询
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    // 未知地址
    public static final String UNKNOWN = "XX XX";

    public static String getRealAddressByIP(String ip)
    {
        // 内网不查询
        if (IpUtil.internalIp(ip))
        {
            return "内网IP";
        }
        Boolean addressEnabled = SpringUtil.getRequiredProperty("primal.common.addressEnabled", Boolean.class);

        if(Objects.nonNull(addressEnabled) && addressEnabled){

            try
            {
                RestTemplate restTemplate = SpringUtil.getBean("customRestTemplate");
                ResponseEntity<String> result = restTemplate.getForEntity(IP_URL + "?ip=" + ip + "&json=true", String.class);
                String rspStr = result.getBody();
                if (StringUtil.isEmpty(rspStr))
                {
                    LogManager.LOG().sys_common_log(AddressUtil.class).error("获取地理位置异常 {}", ip);
                    return UNKNOWN;
                }
                JSONObject obj = JSON.parseObject(rspStr);
                String region = obj.getString("pro");
                String city = obj.getString("city");
                return String.format("%s %s", region, city);
            }
            catch (Exception e)
            {
                LogManager.LOG().sys_common_log(AddressUtil.class).error("获取地理位置异常 {}", ip);
            }

        }

        return UNKNOWN;
    }
}
